import paho.mqtt.client as mqtt
from config import settings


class MqttStatusCode:
    Success = 0


class MqttClientHelper:
    def __init__(self, client_id=None, user=None, password=None):
        self.client = mqtt.Client()
        self.client.reinitialise(client_id=client_id, clean_session=None)
        self.client.username_pw_set(user, password)

        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect

        self.client.connect(host=settings.MqttBroker_PATH, port=1883, keepalive=60)

    def set_callback_function(self, on_connect, on_message):
        self.client.on_connect = on_connect
        self.client.on_message = on_message

    def on_connect(self, client, userdata, flags, rc):
        '''
        参考文档：https://www.jianshu.com/p/b76dbc675141
            0: 连接成功
            1: 连接失败-不正确的协议版本
            2: 连接失败-无效的客户端标识符
            3: 连接失败-服务器不可用
            4: 连接失败-错误的用户名或密码
            5: 连接失败-未授权
            6-255: 未定义.
        '''
        if rc == MqttStatusCode.Success:
            return
        else:
            print("mqtt 连接失败")

    def on_disconnect(self):
        print("mqttclient断开。")
        self.client.reconnect()
        print("mqttclient正在重连。")

    def on_message(self, client, userdata, msg):
        print(msg.topic + " " + str(msg.payload))

    def sub(self, topic: str, qos: int = 0):
        result = self.client.subscribe(topic, qos)
        # result 是(0, 1)为发送成功
        print("状态码{0}\t订阅'{1}'成功".format(result, topic))

    def sub_multiple(self, topics: list):
        '''
        demo
        [{
            "topic":${TOPIC},
            "qos": ${QOS}]
        }]
        '''
        for item in topics:
            print(item)
            result = self.client.subscribe(item["topic"], item["qos"])
            print("状态码{0}\t订阅'{1}'成功".format(result, item["topic"]))

    def unsub(self, topic: str):
        result = self.client.unsubscribe(topic)
        print("状态码{0}\t取消订阅'{1}'成功".format(result, topic))

    def pub(self, topic: str, payload: str, qos: int = 0):
        result = self.client.publish(topic, payload, qos)
        print("状态码{0}\t向‘{1}’成功发送消息：{2}".format(result, topic, payload))

    def loop_forever(self):
        '''保持连接'''
        self.client.loop_forever()

    def loop_start(self):
        self.client.loop_start()